package a_doubleWrite;

/**
 * 162. 寻找峰值
 * 峰值元素是指其值大于左右相邻值的元素。
 * <p>
 * 给你一个输入数组 nums，找到峰值元素并返回其索引。数组可能包含多个峰值，在这种情况下，
 * 返回 任何一个峰值 所在位置即可。
 * <p>
 * 你可以假设 nums[-1] = nums[n] = -∞ 。
 *
 * @author luolidong
 * @version 1.0
 * @create 2021-07-29 09:16
 */
public class L162 {
    public int findPeakElement(int[] nums) {
        if (nums.length == 1) return 0;
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = (right - left) / 2 + left;
            if (nums[mid] < nums[mid + 1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return right;
    }

    public int findPeakElement1(int[] nums) {
        return binarySearch(nums, 0, nums.length - 1);
    }

    private int binarySearch(int[] nums, int left, int right) {
        if (left >= right) {
            return left;
        }
        int mid = (right - left) / 2 + left;
        if (nums[mid] < nums[mid + 1]) {
            return binarySearch(nums, mid + 1, right);
        } else {
            return binarySearch(nums, left, mid);
        }
    }

    public static void main(String[] args) {
        L162 l162 = new L162();
        int peakElement = l162.findPeakElement1(new int[]{1, 2, 1, 3, 5, 6, 4});
        System.out.println(peakElement);
    }
}
